package com.shen.pool;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Demo05 {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,//核心线程数
                5,//最大线程数
                3,//空闲线程存活时间
                TimeUnit.SECONDS,//时间单位
                new LinkedBlockingDeque<>(3),//阻塞方式 双端队列
                Executors.defaultThreadFactory(),//线程工厂
                new ThreadPoolExecutor.DiscardOldestPolicy()
                //当队列满了后，尝试去和最早的线程进行竞争，看他是不是可以让位给新的线程执行，不会爆出错误

        );
        /**
         * pool-1-thread-1 ok
         * pool-1-thread-1 ok
         * pool-1-thread-1 ok
         * pool-1-thread-1 ok
         * pool-1-thread-1 ok
         * pool-1-thread-1 ok
         * pool-1-thread-1 ok
         * pool-1-thread-1 ok
         * pool-1-thread-2 ok
         * pool-1-thread-3 ok
         * pool-1-thread-4 ok
         * pool-1-thread-5 ok
         *
         * 这里打印出12个线程已执行
         * 但我们的线程池最大只能容纳10个线程  最大承载：最大线程数5+阻塞队列3=8
         *
         */
        try {
            for (int i = 0; i < 100; i++) {
                    //使用线程池创建线程
                    threadPoolExecutor.execute(()->{
                        System.out.println(Thread.currentThread().getName()+" ok ");
                    });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //线程池用完关闭线程池
            threadPoolExecutor.shutdown();
        }


    }
}
